package vn.gg.network;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import vn.gg.util.Log;

/**
 * Encode message before send.
 * 
 * @author truongps
 * 
 */
class ServerEncoder implements ProtocolEncoder {

	
	private static final String TAG = "ServerEncoder";
	
	@Override
	public void dispose(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void encode(IoSession ioSession, Object object,
			ProtocolEncoderOutput encoderOutput) throws Exception {
		Log.log("fsdaf", "Sendding");
		Message message = (Message) object;
		// Write chuoi json xuong.
		String json = message.toJson();

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		dos.writeInt(json.length());
		dos.write(json.getBytes("UTF-8"));
		
		byte[] bytes = baos.toByteArray();
		Log.log(TAG, "Total Byte Send: " + bytes.length);
		encoderOutput.write(IoBuffer.wrap(bytes));
//		Log.log("fsdaf", "Sent");
		//baos.close();
		//dos.close();
	}

}
